package com.atguigu.spzx.gateway.filter;

import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.atguigu.spzx.model.result.ResultCodeEnum;
import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {
    //
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、判断请求路径是否需要验证登录状态
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        AntPathMatcher matcher = new AntPathMatcher();
        //1.1 不需要：直接放行
        if(!matcher.match("/**/auth/**" , path)){
            return chain.filter(exchange);
        }
        //1.2 需要:验证
        //2、获取头中的token 到redis中查询登录状态 存在放行不存在返回一个Restful风格的响应报文(响应体设置一个Result对象的json)
        String token = request.getHeaders().getFirst("token");

        //redisTemplate必须和 微服务的配置一样
        if(StringUtils.isEmpty(token) || !redisTemplate.hasKey("spzx:user:login:" + token)){
            //token不存在 或者 token过期
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);//设置状态码
            //设置响应头：指定响应体内容的类型
            response.getHeaders().add("content-type" , MediaType.APPLICATION_JSON_UTF8_VALUE);
            //设置响应体： Result
//            ResultCodeEnum.LOGIN_STATUS_ERROR
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("code", ResultCodeEnum.LOGIN_STATUS_ERROR.getCode());
            jsonObject.addProperty("message", ResultCodeEnum.LOGIN_STATUS_ERROR.getMessage());

            String json = jsonObject.toString();
            DataBuffer buffer = response.bufferFactory().wrap(json.getBytes());
            //返回自定义响应报文：不放行
            return response.writeWith(Mono.just(buffer));

        }
        // 登录状态有效 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
